import { Injectable } from '@angular/core';
import { Http,Headers } from '@angular/http'; //和header相关的要在这里引入
import 'rxjs/add/operator/map';
import{HEROES} from '../../pages/mock-heroes';
import{Hero} from '../../pages/heros/Hrtest.module';


// 引入promise相关   
import 'rxjs/add/operator/toPromise';


//引入observe 
import { Observable }     from 'rxjs/Observable';
/*
  Generated class for the HeroServiceProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class HeroServiceProvider {

  constructor(public http: Http ) {
    console.log('Hello HeroServiceProvider Provider');
  }

  // getHeroes(): void {

  // } // stub


 private heroesUrl = 'api/heroes';  // URL to web api

getHeroes():Promise<Hero[]>{
  //返回一个XX的数组。
  console.log('servicego');
   return Promise.resolve(HEROES);
    //return HEROES;
}


getHeroesSlowly(): Promise<Hero[]> {
  return new Promise(resolve => {
    // Simulate server latency with 2 second delay
    setTimeout(() => resolve(this.getHeroes()), 4000); //mock 4s
  });
}


// 获取数据
getHeroesByMock(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }


  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }

  getHero(id: number): Promise<Hero> {
  const url = `${this.heroesUrl}/${id}`;
  return this.http.get(url)
    .toPromise()
    .then(response => response.json().data as Hero)
    .catch(this.handleError);
}

//保存数据

private headers = new Headers({'Content-Type': 'application/json'});

update(hero: Hero): Promise<Hero> {
  const url = `${this.heroesUrl}/${hero.id}`;
  return this.http
    .put(url, JSON.stringify(hero), {headers: this.headers})
    .toPromise()
    .then(() => hero)
    .catch(this.handleError);
}

// 新增

create(name: string): Promise<Hero> {
  //请求-取消-新请求的序列对于Promise来说是很难实现的，但是对Observable来说则很容易。
  console.log('observer',this.http
    .post(this.heroesUrl, JSON.stringify({name: name}), {headers: this.headers}));
  return this.http
    .post(this.heroesUrl, JSON.stringify({name: name}), {headers: this.headers})
    .toPromise()
    .then(res => res.json().data as Hero)
    .catch(this.handleError);
}


delete(id: number): Promise<void> {
  const url = `${this.heroesUrl}/${id}`;
  return this.http.delete(url, {headers: this.headers})
    .toPromise()
    .then(() => null)
    .catch(this.handleError);
}



search(term: string): Observable<Hero[]> {
  // 这个借口不知道哪里来的数据.......
    return this.http
               .get(`app/heroes/?name=${term}`)
               .map(
                 response => response.json().data as Hero[]);
  }


}
